package com.ybe.handler.exchange;

import com.sun.net.httpserver.HttpExchange;
import com.ybe.handler.exchange.annotation.HttpExchangeAnnotation;
import com.ybe.util.ReflectionUtil;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class HttpExchangeHandlerFactory {

    private static final List<HttpExchangeHandler> httpExchangeHandlers = new ArrayList<>();


    static {
        List<String> classNames = new ArrayList<>();
        try {
            classNames= ReflectionUtil.scanAndGetAllClasses(HttpExchangeHandlerFactory.class.getPackage().getName());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        for(String className : classNames){
            try {
                // 加载类
                Class<?> clazz = Class.forName(className);

                // 检查是否有 @HttpExchangeAnnotation 注解
                if (clazz.isAnnotationPresent(HttpExchangeAnnotation.class)) {

                    // 检查是否是可实例化的类（非接口、非抽象类）
                    if (!clazz.isInterface() && !java.lang.reflect.Modifier.isAbstract(clazz.getModifiers())) {
                        // 获取注解实例
                        HttpExchangeAnnotation annotation = clazz.getAnnotation(HttpExchangeAnnotation.class);

                        // 使用无参构造器创建实例
                        Constructor<?> constructor = clazz.getDeclaredConstructor();
                        constructor.setAccessible(true); // 允许访问私有构造器
                        HttpExchangeHandler instance = (HttpExchangeHandler) constructor.newInstance();

                        // 添加到映射集合，使用类名作为key
                        String key = clazz.getSimpleName();
                        //handlerMap.put(key, instance);
                        httpExchangeHandlers.add(instance);
                    }
                }
            } catch (ClassNotFoundException e) {
                System.out.println("Class not found: " + className + e);
            } catch (NoSuchMethodException e) {
                System.out.println("No public no-arg constructor found for class: {}"+ className + e);
            } catch (InstantiationException e) {
                System.out.println("Failed to instantiate class: {} (abstract class or interface)"+ className + e);
            } catch (IllegalAccessException e) {
                System.out.println("Access denied when instantiating class: {}" + className + e);
            } catch (Exception e) {
                System.out.println("Failed to instantiate class: {}. Error: {}" + className + e.getMessage() + e);
            }
        }

    }




    public static HttpExchangeHandler getMatchHandler(HttpExchange httpExchange) {
        Optional<HttpExchangeHandler> first = httpExchangeHandlers.stream().filter(handler -> handler.isMatch(httpExchange))
                .findFirst();
        return first.orElse(null);
    }

}
